/**
 * This file is part of AudioStream.
 * Copyright (C) 2010 Justin Li and Jacob Wirth
 *
 *  AudioStream is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  AudioStream is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with AudioStream.  If not, see <http://www.gnu.org/licenses/>.
 *  
 */

package org.frustra.audiostream.networking;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;


/**
 * A Socket implementation that automatically sets up input and output streams
 */
public class StreamingSocket
{
	private Socket mySocket = null;
	private OutputStream streamOut = null;
	private Scanner streamIn = null;
	
	public StreamingSocket(String host, int port) throws IOException
	{
		mySocket = new Socket(host, port);
		mySocket.setTcpNoDelay(true);
		streamOut = mySocket.getOutputStream();
		streamIn = new Scanner(mySocket.getInputStream());
	}
	
	public void flush()
	{
		try
		{
			streamOut.flush();
		}
		catch (IOException e) { }
	}
	
	public void close()
	{
		try
		{
			mySocket.shutdownOutput();
			streamIn.close();
			streamOut.close();
			mySocket.close();
		}
		catch (IOException e) { }
	}
	
	public String readLine()
	{
		if (streamIn.hasNextLine())
			return streamIn.nextLine();
		else return null;
	}
	
	public boolean hasInput()
	{
		return streamIn.hasNext();
	}
	
	public void println(String s) throws IOException {
		streamOut.write(s.getBytes());
		streamOut.write("\r\n".getBytes());
	}
	
	public void print(byte[] data) throws IOException
	{
		streamOut.write(data);
	}
}
